<template>
  <div>
    <home-header></home-header>
    <home-swiper :swiperList="swiperList"></home-swiper>
    <home-icons :iconList="iconList"></home-icons>
    <home-recommend :recommendList="recommendList"></home-recommend>
    <home-weekend :weekendList="weekendList"></home-weekend>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import HomeHeader from './components/Header'
import HomeSwiper from './components/Swiper'
import HomeIcons from './components/Icons'
import HomeRecommend from './components/Recommend'
import HomeWeekend from './components/Weekend'
export default {
  name: 'Home',
  components: {
    HomeHeader,
    HomeSwiper,
    HomeIcons,
    HomeRecommend,
    HomeWeekend
  },
  data: function () {
    return {
      lastCity: '',
      iconList: [],
      recommendList: [],
      swiperList: [],
      weekendList: []
    }
  },
  methods: {
    setVal (state) {
      this.iconList = state.HomeIconsData.iconList
      this.recommendList = state.HomeRecommondData.recommendList
      this.swiperList = state.HomeSwiperData.swiperList
      this.weekendList = state.HomeWeekendData.weekendList
    },
    ...mapActions(['chooseCity', 'savePageState']),
    getHomeInfo (shouldUpdate) {
      const homeState = this.pageState.home
      this.lastCity = this.city
      if (homeState && !shouldUpdate) {
        this.setVal(homeState)
      } else {
        const url = `/api/msdk/proxy/query_common_home?city=${this.city}`
        this.$api
          .mockdata(url)
          .then(res => {
            const state = res.data
            let localCity = null
            try {
              if (localStorage.city) {
                localCity = localStorage.city
              }
            } catch (e) {}
            if (localCity) {
              state.HomeHeaderData.city = localCity
            } else {
              this.chooseCity(state.HomeHeaderData.city)
            }
            this.savePageState({
              name: 'home',
              state
            })
            this.setVal(state)
          })
          .catch(e => {
            console.warn(e)
          })
      }
    }
  },
  mounted: function () {
    this.getHomeInfo()
  },
  activated: function () {
    if (this.lastCity !== this.city) {
      this.getHomeInfo(true)
    }
  },
  computed: {
    ...mapState(['pageState', 'city'])
  }
}
</script>

<style></style>
